"""
系统活跃度分析路由
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.analytics import analytics_bp
from app.models.user import User
from app.models.log import SystemLog
from app.models.student_course import StudentCourse
from app.extensions import db
from datetime import datetime, timedelta
import pandas as pd


@analytics_bp.route('/system/activity', methods=['GET'])
@jwt_required()
def get_system_activity():
    """获取系统活跃度数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        # 只有管理员可以查看系统活跃度
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 获取天数参数，默认7天
        days = request.args.get('days', 7, type=int)
        
        # 计算起始日期
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=days)
        
        # 获取日志数据
        logs = SystemLog.query.filter(
            SystemLog.timestamp >= start_date,
            SystemLog.timestamp <= end_date
        ).all()
        
        if not logs:
            return jsonify({
                'success': False,
                'error': 'No activity data available'
            }), 404
        
        # 使用Pandas进行分析
        df = pd.DataFrame([{
            'timestamp': log.timestamp,
            'action': log.action,
            'user_id': log.user_id,
            'level': log.level,
            'status': log.status
        } for log in logs])
        
        # 设置日期为索引
        df['date'] = pd.to_datetime(df['timestamp']).dt.date
        
        # 按日期统计活跃度
        daily_activity = df.groupby('date').agg({
            'user_id': 'nunique',  # 独立用户数
            'action': 'count'       # 操作次数
        }).reset_index()
        
        daily_activity.columns = ['date', 'active_users', 'total_actions']
        
        # 按操作类型统计
        action_stats = df.groupby('action').size().to_dict()
        
        # 按用户统计（Top 10活跃用户）
        user_activity = df.groupby('user_id').size().sort_values(ascending=False).head(10)
        
        top_users = []
        for user_id, count in user_activity.items():
            if user_id:
                u = User.query.get(user_id)
                if u:
                    top_users.append({
                        'user_id': user_id,
                        'username': u.username,
                        'role': u.role,
                        'action_count': int(count)
                    })
        
        # 按小时统计（最近24小时）
        recent_24h = datetime.utcnow() - timedelta(hours=24)
        df_24h = df[pd.to_datetime(df['timestamp']) >= recent_24h].copy()
        df_24h['hour'] = pd.to_datetime(df_24h['timestamp']).dt.hour
        hourly_activity = df_24h.groupby('hour').size().to_dict()
        
        # 按级别统计
        level_stats = df.groupby('level').size().to_dict()
        
        # 成功率统计
        status_stats = df.groupby('status').size().to_dict()
        total_actions = len(df)
        success_rate = (status_stats.get('success', 0) / total_actions * 100) if total_actions > 0 else 0
        
        return jsonify({
            'success': True,
            'data': {
                'daily_activity': daily_activity.to_dict('records'),
                'action_stats': action_stats,
                'top_users': top_users,
                'hourly_activity': hourly_activity,
                'level_stats': level_stats,
                'summary': {
                    'total_actions': int(total_actions),
                    'unique_users': int(df['user_id'].nunique()),
                    'success_rate': float(success_rate),
                    'period_days': days,
                    'start_date': start_date.strftime('%Y-%m-%d'),
                    'end_date': end_date.strftime('%Y-%m-%d')
                }
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/system/enrollment_trend', methods=['GET'])
@jwt_required()
def get_enrollment_trend():
    """获取选课趋势"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        days = request.args.get('days', 30, type=int)
        
        # 计算日期范围
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=days)
        
        # 获取选课数据
        enrollments = StudentCourse.query.filter(
            StudentCourse.created_at >= start_date,
            StudentCourse.created_at <= end_date
        ).all()
        
        if not enrollments:
            return jsonify({
                'success': False,
                'error': 'No enrollment data available'
            }), 404
        
        # 使用Pandas分析
        df = pd.DataFrame([{
            'date': e.created_at.date(),
            'course_id': e.course_id,
            'student_id': e.student_id,
            'status': e.status
        } for e in enrollments])
        
        # 按日期统计
        daily_enrollments = df.groupby('date').size().reset_index()
        daily_enrollments.columns = ['date', 'count']
        
        # 按状态统计
        status_stats = df.groupby('status').size().to_dict()
        
        return jsonify({
            'success': True,
            'data': {
                'daily_trend': daily_enrollments.to_dict('records'),
                'status_distribution': status_stats,
                'total_enrollments': len(enrollments)
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/system/grade_trend', methods=['GET'])
@jwt_required()
def get_grade_trend():
    """获取成绩评定趋势"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        days = request.args.get('days', 30, type=int)
        
        # 计算日期范围
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=days)
        
        # 获取有成绩的选课记录
        graded_courses = StudentCourse.query.filter(
            StudentCourse.graded_at >= start_date,
            StudentCourse.graded_at <= end_date,
            StudentCourse.score.isnot(None)
        ).all()
        
        if not graded_courses:
            return jsonify({
                'success': False,
                'error': 'No grading data available'
            }), 404
        
        # 使用Pandas分析
        df = pd.DataFrame([{
            'date': gc.graded_at.date(),
            'score': float(gc.score),
            'letter_grade': gc.letter_grade
        } for gc in graded_courses if gc.score])
        
        # 按日期统计平均分
        daily_avg = df.groupby('date')['score'].mean().reset_index()
        daily_avg.columns = ['date', 'average_score']
        
        # 按等级统计
        grade_distribution = df['letter_grade'].value_counts().to_dict()
        
        return jsonify({
            'success': True,
            'data': {
                'daily_average': daily_avg.to_dict('records'),
                'grade_distribution': grade_distribution,
                'total_graded': len(graded_courses)
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/system/user_growth', methods=['GET'])
@jwt_required()
def get_user_growth():
    """获取用户增长趋势"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        days = request.args.get('days', 30, type=int)
        
        # 计算日期范围
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=days)
        
        # 获取新增用户
        new_users = User.query.filter(
            User.created_at >= start_date,
            User.created_at <= end_date
        ).all()
        
        if not new_users:
            return jsonify({
                'success': True,
                'data': {
                    'daily_growth': [],
                    'role_distribution': {},
                    'total_new_users': 0
                }
            }), 200
        
        # 使用Pandas分析
        df = pd.DataFrame([{
            'date': u.created_at.date(),
            'role': u.role
        } for u in new_users])
        
        # 按日期统计
        daily_growth = df.groupby('date').size().reset_index()
        daily_growth.columns = ['date', 'new_users']
        
        # 按角色统计
        role_distribution = df.groupby('role').size().to_dict()
        
        return jsonify({
            'success': True,
            'data': {
                'daily_growth': daily_growth.to_dict('records'),
                'role_distribution': role_distribution,
                'total_new_users': len(new_users)
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500







